<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { loginRules } from "./utils/rule";
import { initRouter } from "/@/router/utils";
import { useNav } from "/@/layout/hooks/useNav";
import { message } from "@pureadmin/components";
import type { FormInstance } from "element-plus";
import { storageSession } from "@pureadmin/utils";
import { $t, transformI18n } from "/@/plugins/i18n";
import { useLayout } from "/@/layout/hooks/useLayout";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useTranslationLang } from "/@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "/@/layout/hooks/useDataThemeChange";
import RegisterForm from './register.vue'
import { getTenantId } from '/@/utils/auth'

import { useTenantSelect } from './utils/useTenantSelect'

import { loginApi } from "/@/api/system/user";

import dayIcon from "/@/assets/svg/day.svg?component";
import darkIcon from "/@/assets/svg/dark.svg?component";
import globalization from "/@/assets/svg/globalization.svg?component";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const isRegister = ref(false)

const { initStorage } = useLayout();
initStorage();

const { t } = useI18n();
const { dataTheme, dataThemeChange } = useDataThemeChange();
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();

const ruleForm = reactive({
  phoneNumber: "17666475089",
  password: "123456"
});

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (!getTenantId()) {
          await useTenantSelect(ruleForm)
        }
        await loginApi({
          ...ruleForm,
          tenantId: getTenantId()
        });
        router.push("/");
      } finally {
        loading.value = false;
      }

      // 模拟请求，需根据实际开发进行修改
      // setTimeout(() => {
      // loading.value = false;
      // storageSession.setItem("info", {
      //   phoneNumber: "admin",
      //   accessToken: "eyJhbGciOiJIUzUxMiJ9.test"
      // });
      // initRouter("admin").then(() => {});
      // message.success("登录成功");
      // router.push("/");
      // }, 2000);
    } else {
      loading.value = false;
      return fields;
    }
  });
};

dataThemeChange();

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch v-model="dataTheme" inline-prompt :active-icon="dayIcon" :inactive-icon="darkIcon"
        @change="dataThemeChange" />
      <!-- 国际化 -->
      <el-dropdown trigger="click">
        <globalization
          class="hover:text-primary hover:!bg-[transparent] w-[20px] h-[20px] ml-1.5 cursor-pointer outline-none duration-300" />
        <template #dropdown>
          <el-dropdown-menu class="translation">
            <el-dropdown-item :style="getDropdownItemStyle(locale, 'zh')"
              :class="['dark:!text-white', getDropdownItemClass(locale, 'zh')]" @click="translationCh">
              <IconifyIconOffline class="check-zh" v-show="locale === 'zh'" icon="check" />
              简体中文
            </el-dropdown-item>
            <el-dropdown-item :style="getDropdownItemStyle(locale, 'en')"
              :class="['dark:!text-white', getDropdownItemClass(locale, 'en')]" @click="translationEn">
              <span class="check-en" v-show="locale === 'en'">
                <IconifyIconOffline icon="check" />
              </span>
              English
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <el-form v-if="!isRegister" ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large">
            <Motion :delay="100">
              <el-form-item :rules="[
                {
                  required: true,
                  message: transformI18n($t('login.phoneNumberReg')),
                  trigger: 'blur'
                }
              ]" prop="phoneNumber">
                <el-input clearable v-model="ruleForm.phoneNumber" :placeholder="t('login.phoneNumber')"
                  :prefix-icon="useRenderIcon('user')" />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input clearable show-password v-model="ruleForm.password" :placeholder="t('login.password')"
                  :prefix-icon="useRenderIcon('lock')" />
              </el-form-item>
            </Motion>

            <Motion :delay="250" style="display: flex;justify-content: space-between;">
              <el-link>忘记密码</el-link>
              <el-link @click="isRegister = true">注册</el-link>
            </Motion>

            <Motion :delay="250">
              <el-button class="w-full mt-4" size="default" type="primary" :loading="loading"
                @click="onLogin(ruleFormRef)">
                {{ t("login.login") }}
              </el-button>
            </Motion>
          </el-form>

          <RegisterForm v-else @toLogin="isRegister = false"></RegisterForm>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("/@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}
</style>

<style>
.select-tenant .el-cascader-menu {
  width: 100%;
}
</style>
